package com.ls.lspicturebackend.manger;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.ls.lspicturebackend.config.CosClientConfig;
import com.ls.lspicturebackend.exception.ErrorCode;
import com.ls.lspicturebackend.exception.ThrowUtils;
import com.ls.lspicturebackend.model.dto.file.UploadPictureResult;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    public UploadPictureResult uploadPicture(MultipartFile multipartFile, String uploadPathPrefix) {
        // 图片校验
        validPicture(multipartFile);
        // 图片上传地址
        String uuid = RandomUtil.randomString(16);
        String dateTime = DateUtil.formatDate(new Date());
        String pictureSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        String pictureName = String.format("%s_%s.%s", dateTime, uuid, pictureSuffix);
        String uploadPicturePath = String.format("/%s/%s", uploadPathPrefix, pictureName);
        // 建立临时图片
        File file = null;
        try {
            file = File.createTempFile(uploadPicturePath, null);
            multipartFile.transferTo(file);
            // 上传图片
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPicturePath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            // 信息封装返回
            UploadPictureResult uploadPicture = new UploadPictureResult();
            int pictureWidth = imageInfo.getWidth();
            int pictureHeight = imageInfo.getHeight();
            double pictureScale = NumberUtil.round(pictureWidth * 1.0 / pictureHeight, 2).doubleValue();
            uploadPicture.setUrl(cosClientConfig.getHost() + uploadPicturePath);
            uploadPicture.setPicHeight(pictureHeight);
            uploadPicture.setPicWidth(pictureWidth);
            uploadPicture.setPicScale(pictureScale);
            uploadPicture.setPicSize(FileUtil.size(file));
            uploadPicture.setPicName(FileUtil.mainName(multipartFile.getOriginalFilename()));
            uploadPicture.setPicFormat(imageInfo.getFormat());
            return uploadPicture;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放资源
            this.deleteTempleFile(file);
        }
    }

    public void validPicture(MultipartFile multipartFile) {
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "未上传图片");
        // 图片大小
        long pictureSize = multipartFile.getSize();
        final int ONE_M = 1024 * 1024;
        ThrowUtils.throwIf(pictureSize / ONE_M > 5, ErrorCode.PARAMS_ERROR, "图片大于5M");
        // 文件后缀是否是图片后缀
        final List<String> ALLOW_PICTURE_SUFFIX = Arrays.asList("jpeg", "png", "jpg", "webp");
        String pictureSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!ALLOW_PICTURE_SUFFIX.contains(pictureSuffix), ErrorCode.PARAMS_ERROR, "文件格式不正确");
    }

    public void deleteTempleFile(File file) {
        if (file == null) return;
        boolean delete = file.delete();
        if (!delete) {
            log.error("File delete error, filePath: {}", file.getAbsolutePath());
        }
    }

}
